package com.xxkj.drugtraceability.scan

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.widget.Toast
import com.xxkj.drugtraceability.bean.EventMessage
import com.xxhis.refactor.eventbus.MessageCode
import com.xxhis.refactor.scan.ScanAction
import com.xxkj.drugtraceability.App
import org.greenrobot.eventbus.EventBus

/**
 * Author: mp2
 * Date: 2021/5/12 11:29
 * Describe:扫码广播   直接正则匹配
 * 所有类型都必须通过扫码规则来匹配，包括之前的检验条码，最后没匹配到就是不知道是啥，顶层Activity处理
 */
class ScanReceiver : BroadcastReceiver() {
    lateinit var app: App
    lateinit var mContext: Context

    fun register(context: Context) {
        var filter = IntentFilter()
        ScanAction.scanActionMap.forEach { (key, value) ->
            filter.addAction(key)
        }
        context.registerReceiver(this, filter)
    }

    fun unregister(context: Context) {
        context.unregisterReceiver(this)
    }

    override fun onReceive(context: Context, intent: Intent) {
        app = context.applicationContext as App
        mContext = context
        var key = ScanAction.scanActionMap[intent.action]
        var barcode = intent.getStringExtra(key)
        if (barcode.isNullOrBlank()) {
            return
        }
        //服务端匹配正则结果
//        SoundPlayer.playSound(context)
        val message = barcodeFormat(barcode)
        EventBus.getDefault().post(EventMessage(message, MessageCode.SCAN_BARCODE))
    }
}